package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.entity.SysUser;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.http.UrlUtils;
import com.ecnu.common.utils.uuid.IdUtils;
import com.ecnu.system.domain.*;
import com.ecnu.system.domain.dto.*;
import com.ecnu.system.domain.vo.AnnouncementVO;
import com.ecnu.system.domain.vo.ProjectAnnouncementVO;
import com.ecnu.system.mapper.*;
import com.ecnu.system.service.IEmailService;
import com.ecnu.system.service.IProjectAnnouncementService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * ecnu_活动_资料表 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-03-23
 */
@Service
public class ProjectAnnouncementServiceImpl extends ServiceImpl<ProjectAnnouncementMapper, ProjectAnnouncement> implements IProjectAnnouncementService {
    @Autowired
    private ProjectAnnouncementMapper AnnouncementMapper;
    @Autowired
    private ProjectAnnouncementFileMapper announcementFileMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectUserMapper projectUserMapper;
    @Autowired
    private IEmailService emailService;


    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    protected String getId() {
        return IdUtils.fastSimpleUUID();
    }

    protected String getUuId() {
        return IdUtils.fastUUID();
    }

    @Override
    public AjaxResult edit(ProjectAnnouncementDTO dto, LoginUser loginUser) {
        Project project = projectMapper.selectOne(new QueryWrapper<Project>()
                .eq("id", dto.getProId().toString())
                .eq("del_flag", "0"));
        if (project == null) {
            return AjaxResult.error("活动不存在");
        }
        if (StringUtils.isBlank(dto.getId())) {
            return saveAnnouncement(dto, loginUser,project);//添加
        } else {
            return updateAnnouncement(dto, loginUser);//修改
        }
    }

    @Override
    public TableDataInfo announcementList(AnnouncementDTO dto) {
        Project project = projectMapper.selectOne(new QueryWrapper<Project>()
                .eq("id", dto.getProId().toString())
                .eq("del_flag", "0"));
        if (project == null) {
            return OtherUtil.tableError("活动不存在");
        }
        startPage(dto.getPageDomain());
        List<ProjectAnnouncementVO> vos = AnnouncementMapper.selectlistByProId(dto);

        return OtherUtil.tableSuccess(vos);
    }

    @Override
    public AjaxResult infoById(String id) {
        ProjectAnnouncement announcement = AnnouncementMapper.selectOne(new QueryWrapper<ProjectAnnouncement>()
                .eq("id", id)
                .eq("del_flag", "0"));
        if (announcement == null) {
            return AjaxResult.error("公告不存在");
        }
        AnnouncementVO vo = new AnnouncementVO();
        BeanUtils.copyProperties(announcement, vo);
        List<ProjectAnnouncementFile> proId = announcementFileMapper.selectList(new QueryWrapper<ProjectAnnouncementFile>()
                .eq("pro_id", announcement.getId())
                .orderByAsc("size"));
        if (proId.size() > 0) {
            ArrayList<ProjectIndexFileDTO> collect = new ArrayList<>();
            for (ProjectAnnouncementFile projectAnnouncementFile : proId) {
                ProjectIndexFileDTO indexFileDTO = new ProjectIndexFileDTO();
                BeanUtils.copyProperties(projectAnnouncementFile, indexFileDTO);
                indexFileDTO.setFullurl(UrlUtils.getUrl() + indexFileDTO.getUrl());
                collect.add(indexFileDTO);
            }
            vo.setFileList(collect);
        } else {
            vo.setFileList(new ArrayList<>());
        }

        return AjaxResult.success(vo);
    }

//    public String getUrl() {
//        HttpServletRequest request = ServletUtils.getRequest();
//        return getDomain(request);
//    }
//
//    public static String getDomain(HttpServletRequest request) {
//        StringBuffer url = request.getRequestURL();
//        String contextPath = request.getServletContext().getContextPath();
//        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
//    }

    private AjaxResult saveAnnouncement(ProjectAnnouncementDTO dto, LoginUser loginUser, Project project) {
        try {
            ProjectAnnouncement announcement = new ProjectAnnouncement();
            BeanUtils.copyProperties(dto, announcement);
            announcement.setId(getId());
            if (announcement.getIsTop() == "") {
                announcement.setIsTop("0");
            }
            announcement.setCreateUser(loginUser.getUserId().toString());
            int insert = AnnouncementMapper.insert(announcement);
            if (dto.getAnnouncementFileList() != null && dto.getAnnouncementFileList().size() > 0) {
                extracted(dto, announcement, loginUser);
            }
            //添加成功后，对成员提邮件
            ProjectUser projectUser1 = new ProjectUser();
            projectUser1.setProId(project.getId());
            List<ProjectUser> projectUsers = projectUserMapper.selectListByUser(projectUser1);
            if (CollectionUtils.isNotEmpty(projectUsers)) {
                extracted(project, announcement, projectUsers);
            }

            return AjaxResult.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败,公告名称:\n" + dto.getTitle() + "错误内容为：\n" + e.getMessage());
            return AjaxResult.error("保存失败");
        }
    }

    @Async
    protected void extracted(Project project, ProjectAnnouncement announcement, List<ProjectUser> projectUsers) {
        try {
            //并行流方法发送邮件
            projectUsers.parallelStream()
                    .filter(projectUser -> StringUtils.isNotBlank(projectUser.getEmail()))
                    .forEach(projectUser -> {
                        try {
                        SysUser sysUser = new SysUser();
                        sysUser.setNickName(projectUser.getUserName());
                        sysUser.setEmail(projectUser.getEmail());
                        String title = announcement.getTitle() + "--" + project.getProName();
                        emailService.GeneralEmail(title, announcement.getIntroduction(), sysUser);
                        } catch (Exception innerException) {
                            log.error("发送邮件给 "+projectUser.getUserName()+"--"+projectUser.getEmail()
                                    +"，失败: "+ innerException.getMessage(), innerException);
                        }
                    });
            log.debug("发送邮件给所有用户成功");
        } catch (Exception e) {
            log.error("异步发送邮件失败: " + e.getMessage());
        }
//        }
    }

    /**
     * 保存文件信息
     *
     * @param dto
     * @param announcement
     */
    private void extracted(ProjectAnnouncementDTO dto, ProjectAnnouncement announcement, LoginUser loginUser) {
        announcementFileMapper.delete(new QueryWrapper<ProjectAnnouncementFile>()
                .eq("pro_id", announcement.getId()));
        int count = 1;
        for (ProjectAnnouncementFile fileDTO : dto.getAnnouncementFileList()) {
            fileDTO.setProId(announcement.getId());
            fileDTO.setId(getId());
            fileDTO.setSize(count);
            fileDTO.setCreateUser(loginUser.getUserId().toString());
            announcementFileMapper.insert(fileDTO);
            if(count<=dto.getAnnouncementFileList().size()){
                count++;
            }
        }
    }

    private AjaxResult updateAnnouncement(ProjectAnnouncementDTO dto, LoginUser loginUser) {
        try {
            ProjectAnnouncement announcement = new ProjectAnnouncement();
            BeanUtils.copyProperties(dto, announcement);
            int insert = AnnouncementMapper.updateById(announcement);
            if (dto.getAnnouncementFileList() != null && dto.getAnnouncementFileList().size() > 0) {
                extracted(dto, announcement, loginUser);
            }
            return AjaxResult.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败,公告名称:\n" + dto.getTitle() + "错误内容为：\n" + e.getMessage());
            return AjaxResult.error("保存失败");
        }
    }
}
